/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ControllerAjax;

import GestionBDD.ControllerBDD;
import Main.StaticParams;
import Main.Toolbox;
import Model.Carte;
import Model.Utilisateur;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Sik
 */
@WebServlet(name = "Map", urlPatterns =
{
    "/Map/*"
})
public class ControllerMap extends HttpServlet
{

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String pathInfo = request.getPathInfo();
        String query = request.getQueryString();

        if (pathInfo.equals("/add"))
        {
            String designation = request.getAttribute("designation").toString();
            String filename = request.getAttribute("filename").toString();
            String path = request.getAttribute("path").toString();

            if (designation != null && filename != null)
            {
                Carte c = new Carte();
                c.setDesignation(designation);
                c.setDateDepot(new Date());
                c.setStatut("en cours");
                c.setPath(path);
                List<Carte> lc = (List<Carte>) getServletContext().getAttribute("maps");
                lc.add(c);
                ControllerBDD.getINSTANCE().add(c);

                int idCarte = c.getIdCarte();
                RequestDispatcher rd = getServletContext().getContext(request.getContextPath()).getRequestDispatcher("/Map/edit?idCarte=" + idCarte);
                rd.forward(request, response);
            }
        }
        else if (pathInfo.equals("/list"))
        {
            List<Carte> lc = (List<Carte>) getServletContext().getAttribute("maps");
            request.setAttribute("mapList", lc);
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/listMaps.jsp");
            rd.forward(request, response);
        }
        else if (pathInfo.equals("/delete"))
        {
            int idCarte = Integer.parseInt(request.getParameter("idCarte"));
            Carte c = getMapFromId(idCarte);
            List<Carte> lc = (List<Carte>) getServletContext().getAttribute("maps");
            ControllerBDD.getINSTANCE().remove(c);
            lc.remove(c);
        }
        else if (pathInfo.equals("/update"))
        {
            int idCarte = Integer.parseInt(request.getParameter("idCarte"));
            String designation = request.getParameter("designation");
            String date = request.getParameter("dateMax");
            Date dateMax = null;
            try
            {
                dateMax = Toolbox.stringToDate(date);
            }
            catch (ParseException ex)
            {
                Logger.getLogger(ControllerMap.class.getName()).log(Level.SEVERE, null, ex);
            }

            Carte c = getMapFromId(idCarte);

            if (designation != null)
            {
                c.setDesignation(designation);
            }
            if (dateMax != null)
            {
                c.setDateExpiration(dateMax);
            }

            ControllerBDD.getINSTANCE().update(c);
        }
        else if (pathInfo.equals("/view"))
        {
            int idCarte = 0;
            if ((query != null) && query.contains("idCarte"))
            {
                String id = Toolbox.ExtractParameterFromQuery(query, "idCarte");
                if (id != null)
                {
                    idCarte = Integer.parseInt(id);
                }
            }
            else
            {
                idCarte = (Integer) request.getSession().getAttribute("idCarte");
            }

            Carte c = getMapFromId(idCarte);
            
            String relPath = c.getPath().replaceAll("/", Matcher.quoteReplacement("\\"));
            BufferedImage img = ImageIO.read(new File(getServletContext().getRealPath("") + relPath));
            
            int height = img.getHeight();
            int width = img.getWidth();
            request.getSession().setAttribute("height", height);
            request.getSession().setAttribute("width", width);
            request.getSession().setAttribute("carte", c.xmlParse(true));
            request.getSession().setAttribute("mapFilePath", getServletContext().getContextPath() + c.getPath());
            request.getSession().setAttribute("contextPath", getServletContext().getContextPath());

            response.sendRedirect(getServletContext().getContextPath() + "/mapView.jsp");
        }
        else if (pathInfo.equals("/edit"))
        {
            int idCarte = 0;
            if ((query != null) && query.contains("idCarte"))
            {
                String id = Toolbox.ExtractParameterFromQuery(query, "idCarte");
                if (id != null)
                {
                    idCarte = Integer.parseInt(id);
                }
            }
            else
            {
                idCarte = (Integer) request.getSession().getAttribute("idCarte");
            }

            Carte c = getMapFromId(idCarte);
            
            String relPath = c.getPath().replaceAll("/", Matcher.quoteReplacement("\\"));
            BufferedImage img = ImageIO.read(new File(getServletContext().getRealPath("") + relPath));
            
            int height = img.getHeight();
            int width = img.getWidth();
            request.getSession().setAttribute("height", height);
            request.getSession().setAttribute("width", width);
            request.getSession().setAttribute("carte", c.xmlParse(true));
            request.getSession().setAttribute("mapFilePath", getServletContext().getContextPath() + c.getPath());
            request.getSession().setAttribute("contextPath", getServletContext().getContextPath());

            response.sendRedirect(getServletContext().getContextPath() + "/mapEditor.jsp");
        }
        else if (pathInfo.equals("/import"))
        {
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/mapImport.jsp");
            rd.forward(request, response);

        }
    }
    

    private void setUpResponse(HttpServletResponse response, Carte c) throws IOException
    {
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        response.getWriter().write(c.xmlParse(false));
        response.getWriter().close();
    }

    public Carte getMapFromId(int id)
    {
        List<Carte> lc = (List<Carte>) getServletContext().getAttribute("maps");

        for (Carte c : lc)
        {
            if (c.getIdCarte() == id)
            {
                return c;
            }
        }
        return null;
    }

    public List<Carte> getReachedMapForUser(Utilisateur u)
    {
        List<Carte> lc = (List<Carte>) getServletContext().getAttribute("maps");
        List<Carte> list = new ArrayList<Carte>();
        for (Carte c : lc)
        {
            if (c.getUtilisateurList().contains(u))
            {
                list.add(c);
            }
        }
        return list;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }// </editor-fold>
}
